/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2020.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2020年2月19日    Zhao Haiming         Create the class
 * http://www.jimilab.com/
*/

package com.futuremap.ws.service;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.futuremap.ws.bean.APIContent;
import com.futuremap.ws.bean.WebSocketBean;
import com.futuremap.ws.constant.API;
import com.futuremap.ws.constant.CommonConstant;
import com.futuremap.ws.util.ChannelSupervise;

/**
 * @FileName WebSocketService.java
 * @Description: 
 *
 * @Date 2020年2月19日 下午1:55:17
 * @author Zhao Haiming
 * @version 1.0
 */
@Service
public class WebSocketService {
	
	private static final Logger log = LoggerFactory.getLogger(WebSocketService.class);
	
	public void sendMsg(String userId, String msg)
	{
		List<Channel> channelList = ChannelSupervise.getChannel(userId);
		if(channelList != null)
		{
			for(Channel channel : channelList)
			{
				if(channel.isActive())
				{
					log.info("sendMsg:userId={},appId={},msg={}",userId,channel.attr(CommonConstant.appIdAK).get(),
							msg);
					channel.writeAndFlush(new TextWebSocketFrame(msg));
				}
				else
				{
					log.info("sendMsgChannelInActive:userId={},appId={},msg={}",userId,
							channel.attr(CommonConstant.appIdAK).get(),msg);
					ChannelSupervise.unRegisterChannel(userId, channel);
				}
			}
		}
		else
		{
			log.info("sendMsgNoChannel:userId={},msg={}",userId,msg);
		}
	}
	
	public WebSocketBean getParamFromUri(String uri)
	{
		WebSocketBean wsBean = new WebSocketBean();
		if(uri.contains("?"))
    	{
    		String[] uriArray = uri.split("\\?");
			if (null != uriArray && uriArray.length > 1) {
				String [] paramsArray = uriArray[1].split("&");
				for(String param : paramsArray)
				{
					String[] paramArray = param.split("=");
					if (null != paramArray && paramArray.length > 1) {
						switch(paramArray[0])
						{
							case "appId":
								wsBean.setAppId(paramArray[1]);
								break;
							case "userId":
								wsBean.setUserId(paramArray[1]);
								break;
							case "devSecret":
								wsBean.setDevSecret(paramArray[1]);
								break;
							case "devKey":
								wsBean.setDevKey(paramArray[1]);
								break;
							case "appType":
								wsBean.setAppType(Integer.parseInt(paramArray[1]));
								break;
						}
					}
				}
			}

    	}
		return wsBean;
	}
	
	public TextWebSocketFrame executeMsg(WebSocketBean msgBean)
	{
		TextWebSocketFrame tws = new TextWebSocketFrame(JSON.toJSONString(msgBean));
		return tws;
	}

	public APIContent checkParam(WebSocketBean wsBean)
    {
		APIContent apiContent = new APIContent();
		
    	if(StringUtils.isBlank(wsBean.getUserId()))
    	{
    		apiContent.setCode(API.USERID_NOT_EXIST);
    		apiContent.setMsg(API.MSG.get(API.USERID_NOT_EXIST)+",连接将在3秒后关闭");
    		return apiContent;
    	}
    	if(StringUtils.isBlank(wsBean.getAppId()))
    	{
    		apiContent.setCode(API.APPID_NOT_EXIST);
    		apiContent.setMsg(API.MSG.get(API.APPID_NOT_EXIST)+",连接将在3秒后关闭");
    		return apiContent;
    	}
    	if(StringUtils.isBlank(wsBean.getDevKey()))
    	{
    		apiContent.setCode(API.DEV_KEY_NOT_EXIST);
    		apiContent.setMsg(API.MSG.get(API.DEV_KEY_NOT_EXIST)+",连接将在3秒后关闭");
    		return apiContent;
    	}
    	if(StringUtils.isBlank(wsBean.getDevSecret()))
    	{
    		apiContent.setCode(API.DEV_SECRET_NOT_MATCH);
    		apiContent.setMsg(API.MSG.get(API.DEV_SECRET_NOT_MATCH)+",连接将在3秒后关闭");
    		return apiContent;
    	}

    	apiContent.setCode(API.SUCCESS);
    	return apiContent;
    }
}
